<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="80%">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
      disabled
    >
      <el-form-item label="部门" prop="deptId">
        <el-input v-model="formData.deptName" placeholder="请输入部门" />
      </el-form-item>
      <el-form-item label="用户" prop="userId">
        <el-input v-model="formData.userName" placeholder="请输入用户" />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="formData.status" placeholder="状态" clearable class="!w-240px">
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.PSY_TEST_STATUS)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="评价结果" prop="result">
        <el-input v-model="formData.result" placeholder="请输入结果" />
      </el-form-item>
    </el-form>
    <!-- 子表的表单 -->
    <el-tabs v-model="subTabsName">
      <el-tab-pane label="测试信息" name="testItem">
        <TestItemForm ref="testItemFormRef" :psy-test-id="formData.id" />
      </el-tab-pane>
    </el-tabs>
    <!-- <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template> -->
  </Dialog>
</template>
<script setup lang="ts">
import { TestApi, TestVO } from '@/api/psy/test'
import TestItemForm from './components/TestItemForm.vue'
import { DICT_TYPE, getIntDictOptions, getStrDictOptions } from '@/utils/dict'
import { result } from 'lodash-es'
/** 心理测试 表单 */
defineOptions({ name: 'TestForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  deptId: undefined,
  userId: undefined,
  name: undefined,
  score: undefined,
  result: undefined,
  createTime: undefined,
})
const formRules = reactive({
  // name: [{ required: true, message: '名字不能为空', trigger: 'blur' }],
  // score: [{ required: true, message: '分数不能为空', trigger: 'blur' }],
})
const formRef = ref() // 表单 Ref

/** 子表的表单 */
const subTabsName = ref('testItem')
const testItemFormRef = ref()

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  dialogTitle.value = '查看'
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await TestApi.getTest(id)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 校验子表单
  try {
    await testItemFormRef.value.validate()
  } catch (e) {
    subTabsName.value = 'testItem'
    return
  }
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as TestVO
    // 拼接子表的数据
    data.testItems = testItemFormRef.value.getData()
    if (formType.value === 'create') {
      await TestApi.createTest(data)
      message.success(t('common.createSuccess'))
    } else {
      await TestApi.updateTest(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    deptId: undefined,
    userId: undefined,
    name: undefined,
    score: undefined
  }
  formRef.value?.resetFields()
}
</script>
